package com.wangzhen.abstractroutingdatasource.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 数据源切换（读、写）
 * 利用ThreadLocal保存当前线程是否处于读模式
 * 通过设置READ_ONLY注解在开始操作前设置模式为读模式，操作结束后清除该数据，避免内存泄漏，同时也为了后续在该线程进行写操作时任然为读模式
 */
public class DataSourceContextHolder {

    private static Logger logger = LoggerFactory.getLogger(DataSourceContextHolder.class);

    public static final String WRITE = "write";
    public static final String READ = "read";

    private static ThreadLocal<String> contextHolder= new ThreadLocal<>();

    public static void setDataSOurceType(String dataSourceType) {
        if (dataSourceType == null) {
            logger.error("dataSource type为空");
            throw new NullPointerException();
        }
        logger.info("设置dataSource type为：{}", dataSourceType);
        contextHolder.set(dataSourceType);
    }

    /**
     * 默认写模式
     * @return
     */
    public static String getDataSourceType() {
        return contextHolder.get() == null ? WRITE : contextHolder.get();
    }

    public static void clearDataSourceType() {
        contextHolder.remove();
    }
}
